package com.examples.rabbitmqapi;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeoutException;

/**
 * @author benjamin
 * created at 2020-01-26
 */
public class Producer {
    /**
     * 1、 创建连接工厂
     * 2、设置RabbitMQ地址
     * <p>
     * 3、建立到代理服务器的连接
     * <p>
     * 4、创建信道
     * <p>
     * 5、 声明交换器
     * <p>
     * 6、发布消息
     * <p>
     * 7、关闭信道和连接
     */

    public static void main(String[] args) {
        ConnectionFactory factory = new ConnectionFactory();

        factory.setUsername("guest");
        factory.setPassword("guest");

        factory.setHost("localhost");
        factory.setVirtualHost("/");

        try {
            Connection connection = factory.newConnection();

            Channel channel = connection.createChannel();

            // queue声明
            String queue01 = channel.queueDeclare("queue01",
                    true, false, false, null).getQueue();


            String exchange01 = "exchange01";

            // 交换器声明
            channel.exchangeDeclare(exchange01, "direct", true);

            String routingKey01 = "routingKey01";

            // 通过routingkey绑定exchange和queue
            channel.queueBind(queue01, exchange01, routingKey01);

            //Enables publisher acknowledgements on this channel.
            channel.confirmSelect();


            byte[] bytes = "hello world".getBytes();

            new Timer()
                    .schedule(new TimerTask() {
                        @Override
                        public void run() {

                            // 在消费者中创建了队列
                            // 交换机根据路由规则路由到队列
                            try {
                                channel.basicPublish(exchange01, routingKey01,
                                        // Message持久化
                                        MessageProperties.PERSISTENT_TEXT_PLAIN, bytes);


                                // 普通确认
                                boolean waitForConfirms = channel.waitForConfirms();


                                System.out.println("publisher waitForConfirms: " + waitForConfirms);


                            } catch (IOException | InterruptedException e) {
                                e.printStackTrace();
                            }


                        }
                    }, 0L, 1000L);


//            channel.close();
//            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
